package com.example.huajia.wx.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.example.huajia.wx.db.dao.DynamicDao;
import com.example.huajia.wx.db.pojo.CommentEntity;
import com.example.huajia.wx.db.pojo.DynamicEntity;
import com.example.huajia.wx.service.DynamicService;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.example.huajia.wx.common.util.RedisKey.*;

@Service
public class DynamicServiceImpl implements DynamicService {

    @Resource
    DynamicDao dynamicDao;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public String insertDynamic(DynamicEntity entity) {
        Date now = new Date();
        DateUtil.offset(now, DateField.HOUR, 8);
        entity.setCreateTime(DateTime.now().toString());
        entity.setUpdateTime(DateTime.now().toString());
        String city = entity.getCity();
        String key = DYNAMIC_ALL_KEY + city + ":";
        redisTemplate.expire(key, 0, TimeUnit.SECONDS);
        return dynamicDao.insert(entity);
    }

    @Override
    public List<DynamicEntity> searchDynamic(String content) {
        Criteria criteria = Criteria.where("content").regex(".*" + content + ".*");
        return dynamicDao.search(criteria);
    }

    @Override
    public List<DynamicEntity> searchCityWide(String city) {
        Criteria criteria = Criteria.where("city").is(city);
        List<DynamicEntity> list = dynamicDao.search(criteria);
        String key = DYNAMIC_ALL_KEY + city + ":";
        for (DynamicEntity dynamicEntity : list) {
            redisTemplate.opsForList().rightPush(key, dynamicEntity);
        }
        redisTemplate.expire(key, 30, TimeUnit.MINUTES);
        return list;
    }

    @Override
    public List<DynamicEntity> searchMyDynamic(String userId) {
        Criteria criteria = Criteria.where("promulgator").is(userId);
        List<DynamicEntity> list = dynamicDao.search(criteria);
        //查询到数据之后要将数据存储到redis中去
        String key = DYNAMIC_MINE_KEY + userId + ":";
        for (DynamicEntity dynamicEntity : list){
            redisTemplate.opsForList().rightPush(key, dynamicEntity);
        }
        redisTemplate.expire(key, 30, TimeUnit.MINUTES);
        return list;
    }

    @Override
    public List<DynamicEntity> searchHotDynamic() {
        Criteria criteria = new Criteria();
        List<DynamicEntity> list = dynamicDao.search(criteria);
        //先排序，根据评论的数量排序
        Collections.sort(list, new Comparator<DynamicEntity>() {
            @Override
            public int compare(DynamicEntity o1, DynamicEntity o2) {
                if (o2.getCommentsCount() != o1.getCommentsCount()) {
                    return o2.getCommentsCount() - o1.getCommentsCount();
                } else {
                    return o2.getLikeCount() - o1.getLikeCount();
                }
            }
        });
        //查询到数据之后要将数据存储到redis中去
        String key = DYNAMIC_HOT_KEY;
        for (DynamicEntity dynamicEntity : list){
            redisTemplate.opsForList().rightPush(key, dynamicEntity);
        }
        redisTemplate.expire(key, 10, TimeUnit.MINUTES);
        return list;
    }

    @Override
    public DynamicEntity detail(String id) {
        return dynamicDao.detail(id);
    }

    @Override
    public String insertComment(String dynamicId, CommentEntity comment) {
        Date now = new Date();
        DateUtil.offset(now, DateField.HOUR, 8);
        comment.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now));
        comment.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now));
        comment.setId(dynamicId + "#" + IdWorker.getIdStr(CommentEntity.class));//设置uuid
        dynamicDao.insertSubList(dynamicId, "comment", comment);
        String key1 = DYNAMIC_ALL_KEY + comment.getCity() + ":";
        String key2 = DYNAMIC_MINE_KEY + comment.getPromulgator() + ":";
        redisTemplate.expire(key1, 0, TimeUnit.SECONDS);
        redisTemplate.expire(key2, 0, TimeUnit.SECONDS);
        return comment.getId();
    }

    @Override
    public long deleteComment(String dynamicId, String commentId) {
        DynamicEntity dynamic = detail(dynamicId);
        List<CommentEntity> list = dynamic.getComments();
        CommentEntity comment = null;
        for (int i = 0; i < list.size(); i++) {
            if (String.valueOf(list.get(i).getId()).equals(commentId)) {
                comment = list.get(i);
            }
        }
        if (comment == null)
            return 0L;
        return dynamicDao.deleteSubList(dynamicId, "comment", comment);
    }

    public List<CommentEntity> getComments(String dynamicId) {
        String key = DYNAMICS_COMMENTS_KEY + dynamicId + ":";
        List<CommentEntity> list = dynamicDao.getComments(dynamicId);
        for (CommentEntity comment : list){
            redisTemplate.opsForList().rightPush(key, comment);
        }
        redisTemplate.expire(key, 30, TimeUnit.MINUTES);
        return list;
    }

    public List<CommentEntity> getHotComments(String dynamicId) {
        String key = DYNAMICS_HOT_COMMENTS_KEY + dynamicId + ":";
        List<CommentEntity> list = dynamicDao.getComments(dynamicId);
        Collections.sort(list, new Comparator<CommentEntity>() {
            @Override
            public int compare(CommentEntity o1, CommentEntity o2) {
                return o2.getLikeCount() - o1.getLikeCount();
            }
        });
        for (CommentEntity comment : list){
            redisTemplate.opsForList().rightPush(key, comment);
        }
        redisTemplate.expire(key, 30, TimeUnit.MINUTES);
        return list;
    }

    @Override
    public long insertLike(String dynamicId, String userId) {
        return dynamicDao.insertSubList(dynamicId, "like", userId);
    }

    @Override
    public long insertCommentLike(String dynamicId, String userId, String commentId) {
        return dynamicDao.insertCommentSubList(dynamicId, "like", commentId, userId);
    }

    @Override
    public long deleteLike(String dynamicId, String userId) {
        return dynamicDao.deleteSubList(dynamicId, "like", userId);
    }

    @Override
    public long deleteCommentLike(String dynamicId, String userId, String commentId) {
        return dynamicDao.deleteCommentSubList(dynamicId, "like", commentId, userId);
    }

    @Override
    public long deleteDynamicById(String id) {
        return dynamicDao.update(id, new HashMap() {{
            put("deleted", true);
        }});
    }


}
